import { PageContainer, ProCard } from '@ant-design/pro-components';
import { message, Statistic } from 'antd';
import RcResizeObserver from 'rc-resize-observer';
import { useModel } from '@umijs/max';
import { Card, Row, Col, Flex, Button } from 'antd';
import React, { useEffect, useState } from 'react';

import { auditOrderAuth, getHomeData } from '@/services/ant-design-pro/api';
import { ArrowRightOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { ModalForm, ProDescriptions, ProTable } from '@ant-design/pro-components';
import '@umijs/max';

const { Divider } = ProCard;

const Dashboard: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [responsive, setResponsive] = useState(false);
  const [, setSelectedRows] = useState<API.OrderData[]>([]);
  const [orders, setOrders] = useState<API.OrderData[]>([]);
  const [currentOrder, setCurrentOrder] = useState<API.OrderData>({});

  // 授权的modal
  const [authModalOpen, setAuthModalOpen] = useState(false);

  const handleGetHomeData = () => {
    getHomeData().then((res) => {
      setOrders(res.orderlist || []);
    });
  };

  useEffect(() => {
    handleGetHomeData();
  }, []);

  const columns: ProColumns<API.OrderData>[] = [
    {
      title: '工单ID',
      dataIndex: 'WorkOrderID',
      valueType: 'textarea',
    },
    {
      title: '流水号',
      dataIndex: 'SerialNum',
      tooltip: '授权请求的流水号',
    },
    {
      title: '门架',
      dataIndex: 'PortalName',
      sorter: true,
    },
    {
      title: '门架编号',
      dataIndex: 'PortalCode',
    },
    {
      title: '组织',
      sorter: true,
      dataIndex: 'Owner',
    },
    {
      title: '状态',
      sorter: true,
      dataIndex: 'Status',
    },
    {
      title: '授权时间',
      sorter: true,
      dataIndex: 'AuthTime',
      valueType: 'dateTime',
    },
    {
      title: '积分',
      sorter: true,
      dataIndex: 'Points',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, order) => [
        <a
          key={order.ID}
          // TODO: 这里应该最好后台给状态码,或者就固定这个文字别再变了
          disabled={order.Status === '已授权'}
          onClick={() => {
            setAuthModalOpen(true);
            setCurrentOrder(order);
          }}
        >
          授权
        </a>,
      ],
    },
  ];
  return (
    <PageContainer>
      <Row gutter={[16, 10]}>
        <Col flex={'auto'} order={responsive ? 1 : 0}>
          <Card
            style={{
              borderRadius: 8,
            }}
            bodyStyle={{
              paddingTop: 15,
              paddingBottom: 15,
              backgroundImage:
                initialState?.settings?.navTheme === 'realDark'
                  ? 'background-image: linear-gradient(75deg, #1A1B1F 0%, #191C1F 100%)'
                  : 'background-image: linear-gradient(75deg, #FBFDFF 0%, #F5F7FF 100%)',
            }}
          >
            <RcResizeObserver
              key="resize-observer"
              onResize={(offset) => {
                setResponsive(offset.width < 596);
              }}
            >
              <ProCard.Group title="核心指标" direction={responsive ? 'column' : 'row'}>
                <ProCard key={1}>
                  <Statistic title="待授权" value={79} />
                </ProCard>
                <Divider type={responsive ? 'horizontal' : 'vertical'} />
                <ProCard key={2}>
                  <Statistic
                    title="已授权"
                    value={112893}
                    // precision={2}
                  />
                </ProCard>
                <Divider type={responsive ? 'horizontal' : 'vertical'} />
                <ProCard>
                  <Statistic
                    title="稽核工单"
                    value={93}
                    // suffix="/ 100"
                  />
                </ProCard>
                <Divider type={responsive ? 'horizontal' : 'vertical'} />
                <ProCard key={3}>
                  <Statistic title="区块" value={112893} />
                </ProCard>
                <Divider type={responsive ? 'horizontal' : 'vertical'} />
                <ProCard key={4}>
                  <Statistic title="积分" value={456.0} />
                </ProCard>
              </ProCard.Group>
            </RcResizeObserver>
          </Card>
        </Col>
        <Col flex={responsive ? '100%' : '300px'} order={responsive ? 0 : 1}>
          <Card
            style={{
              borderRadius: 8,
            }}
            bodyStyle={{
              // paddingBottom: 16,
              backgroundImage:
                initialState?.settings?.navTheme === 'realDark'
                  ? 'background-image: linear-gradient(75deg, #1A1B1F 0%, #191C1F 100%)'
                  : 'background-image: linear-gradient(75deg, #FBFDFF 0%, #F5F7FF 100%)',
            }}
          >
            <Flex vertical gap={10}>
              <Flex key={1} justify={'space-between'} gap={20}>
                <span>账号:</span>
                <span>Johnson Ma</span>
              </Flex>
              <Flex key={2} justify={'space-between'} gap={20}>
                <span>登录IP:</span>
                <span>120.23.44.11</span>
              </Flex>
              <Flex key={3} justify={'space-between'} gap={20}>
                <span>登录时间:</span>
                <span>2024-07-03 18:43:22</span>
              </Flex>
              <Flex key={4} justify={'space-between'} gap={20}>
                <span>角色:</span>
                <span>管理员</span>
              </Flex>
            </Flex>
          </Card>
        </Col>
      </Row>
      <div>&nbsp;</div>
      <Row gutter={[16, 10]}>
        <Col flex={'auto'} order={responsive ? 1 : 0}>
          <ProTable<API.OrderData>
            headerTitle={'授权操作'}
            rowKey={'ID'}
            search={false}
            options={false}
            toolBarRender={() => [
              <Button
                type="primary"
                key="primary"
                onClick={() => {
                  message.warning('当前版本未实现');
                }}
              >
                批量授权操作
                <ArrowRightOutlined />
              </Button>,
            ]}
            columns={columns}
            dataSource={orders}
            rowSelection={{
              onChange: (_, selectedRows) => {
                setSelectedRows(selectedRows);
              },
            }}
          />
        </Col>
      </Row>

      <ModalForm
        title="授权工单"
        width="400px"
        open={authModalOpen}
        onOpenChange={setAuthModalOpen}
        onFinish={async () => {
          const res = await auditOrderAuth({
            serialnum: currentOrder.SerialNum,
          });
          if (res.no === '0') {
            setAuthModalOpen(false);
            handleGetHomeData();
            message.success('授权成功!');
          } else if (res.no === '4602') {
            setAuthModalOpen(false);
            handleGetHomeData();
            message.warning('当前工单已经授权!');
          } else {
            setAuthModalOpen(false);
            message.error('授权失败!');
          }
        }}
      >
        <ProDescriptions column={1}>
          <ProDescriptions.Item label="工单ID">{currentOrder.WorkOrderID}</ProDescriptions.Item>
          <ProDescriptions.Item label="门架">{currentOrder.PortalName}</ProDescriptions.Item>
          <ProDescriptions.Item label="门架编号">{currentOrder.PortalCode}</ProDescriptions.Item>
          <ProDescriptions.Item label="流水号">{currentOrder?.SerialNum}</ProDescriptions.Item>
          <ProDescriptions.Item label="组织">{currentOrder.Owner}</ProDescriptions.Item>
          <ProDescriptions.Item label="积分">{currentOrder.Points}</ProDescriptions.Item>
        </ProDescriptions>
      </ModalForm>
    </PageContainer>
  );
};

export default Dashboard;
